package com.cuit.xsc.weishare.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ImageCacheList {
	private List<String> urlList = new ArrayList<String>();
	private static final long serialVersionUID = 1L;
	
	public boolean isCached(String url){	
		return urlList.contains(url);
	}

	public void cacheImage(String fileName, InputStream in) {
        OutputStream out = null;
        try {
           // File f = new File(SoapApplication.getInstance().getCacheDir().getPath() + '/' + fileName);
//        	String name[] = fileName.split("/");
//        	 File f = new File(FileUtil.imgFilePath,name[name.length - 1]);
        	fileName = changeFileName(fileName);
        	File f = new File(FileUtil.imgFilePath, fileName);
            if (f.exists()) {
            	return;
//                f.delete();
            }
            LogUtil.i(this, "save filePath->"+f.getPath());
            f.createNewFile();
            urlList.add(fileName); // ADD
            out = new FileOutputStream(f);
            byte[] buffer = new byte[2048];
            int n;
            while ((n = in.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
        } catch (Exception ex) {
        	ex.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public Bitmap getImageFromCache(String fileName) {
        try {
//            File f = new File(SoapApplication.getInstance().getCacheDir().getPath() + '/' + fileName);
//        	String name[] = fileName.split("/");
//        	File f = new File(FileUtil.imgFilePath,name[name.length - 1]);
        	fileName = changeFileName(fileName);
        	File f = new File(FileUtil.imgFilePath,fileName);
        	LogUtil.i(this, "find filePath->"+f.getPath());
            if (f.exists()) {
                return BitmapFactory.decodeFile(f.getAbsolutePath());
            }
        } catch (Throwable ignore) {
        }
        return null;
    }
    
    public String changeFileName(String fileName)
    {
    	if (fileName != null)
		{
			fileName = fileName.replace(":", "").replaceAll("/", "").replaceAll("\\.", "");
			return fileName;
		}
    	
    	return null;
    }
}
